#include "delay.h"

bool is_timeout(void)
{
    if (SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) {
        SysTick->CTRL = 0;
        return 1;//TRUE
    }
    else {
        return 0;//FALSE
    }
}

static void set_timeout_usec(uint32_t n)
{
    uint32_t ticks = n * (48000000 / 1000000);

    SysTick->CTRL = 0;
    /* set reload value register */
    SysTick->LOAD = (ticks & SysTick_LOAD_RELOAD_Msk) - 1;
    /* set current value register */
    SysTick->VAL = 0;
    /* enable SysTick timer and use internal clock source */
    SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_CLKSOURCE_Msk;
}
//void Delay_us(uint32_t n)
//{
//    set_timeout_usec(n);
//    while (!is_timeout());
//}

void Delay_us(uint32_t n)
{
    for(u32 i=0;i<n;i++)
	{
		__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
		__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
		__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
		__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
	}
}

void Delay_ms(uint32_t n)
{
    uint16_t count;
    if(n !=0)
    {
        for (count = 0; count <n; count++)
        {
            Delay_us(1000);//1ms
        }
    }
}


void TIM1_Configure(void)
{
    NVIC_InitTypeDef        NVIC_InitStruct;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

    RCC_ClocksTypeDef RCC_Clocks;

    RCC_GetClocksFreq(&RCC_Clocks);

    RCC_APB1PeriphClockCmd(RCC_APB1ENR_TIM1, ENABLE);

    TIM_TimeBaseStructInit(&TIM_TimeBaseInitStruct);
    TIM_TimeBaseInitStruct.TIM_Prescaler         = (RCC_Clocks.PCLK1_Frequency / 1000000 - 1);
    TIM_TimeBaseInitStruct.TIM_CounterMode       = TIM_CounterMode_Up;
    TIM_TimeBaseInitStruct.TIM_Period            = (1000 - 1);
    TIM_TimeBaseInitStruct.TIM_ClockDivision     = TIM_CKD_DIV1;
    TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStruct);

    TIM_ClearFlag(TIM1, TIM_FLAG_Update);
    TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);

    NVIC_InitStruct.NVIC_IRQChannel = TIM1_BRK_UP_TRG_COM_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPriority = 0x01;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);

    TIM_Cmd(TIM1, ENABLE);
}





